package ec_si_template;

import java.io.BufferedWriter;
import java.io.FileWriter;

/**
 * Class used for saving current position of individuals to text file
 * 
 * @author Andreas Janecek
 * 
 */
public class MyFileWriter {
	/**
	 * the filename
	 */
	private String fileName = "";

	/**
	 * Initialize an object of this class and set the private variable fileName
	 * 
	 * @param fileName
	 *            the filename
	 */
	public MyFileWriter(String fileName) {
		this.fileName = fileName;
	}

	/**
	 * Append a the string 'line' to the file by opening the file, writing the
	 * line, and closing the file again. Possibly not the fastest version to
	 * append an array to a file but be sufficiently fast
	 * 
	 * @param line
	 *            a single line that should be appended to the file
	 */
	public void append(String line) {
		// remove [ and ] at the beginning and the end of the string
		line = line.replace('[', '\0');
		line = line.replace(']', '\0');
		line = line.trim();

		try {
			// Create file
			FileWriter fstream = new FileWriter(this.fileName, true);
			BufferedWriter out = new BufferedWriter(fstream);

			out.write(line + "\n");
			// Close the output stream
			out.close();
		} catch (Exception e) {// Catch exception if any
			System.err.println("Error: " + e.getMessage());
		}
	}
}